package guoanmaker.provider.business.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import javax.transaction.Transactional;

import org.springframework.transaction.annotation.Isolation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;

import guoanmaker.provider.business.model.OperatorServerClass;
import guoanmaker.provider.business.model.PersonalUser;
import guoanmaker.provider.business.model.PerviderDictionary;
import guoanmaker.provider.business.model.ProviderBusiness;
import guoanmaker.provider.business.model.ProviderBusinessServerRange;
import guoanmaker.provider.business.repository.ProviderBusinessRepository;
import guoanmaker.provider.business.service.OperatorServerClassService;
import guoanmaker.provider.business.service.ProviderBusinessServiceIntegerface;
import guoanmaker.provider.business.service.ProviderDictionaryServiceInterface;
import guoanmaker.provider.helper.common.AjaxJson;
import guoanmaker.provider.helper.common.util.OSSUnitHelper;
import io.swagger.annotations.ApiOperation;
/**
 * 
* @ClassName: ProviderBusinessController
* @Description:企业认证 (这里用一句话描述这个类的作用) 
* @author lihongyu
* @date 2017年7月6日 上午10:37:29 
*  
 */
@RestController
public class ProviderBusinessController {
	@Autowired
	private ProviderBusinessServiceIntegerface providerBusinessServiceIntegerface;
	@Autowired
	private ProviderBusinessRepository providerBusinessRepository;
	
	@Autowired
	private ProviderDictionaryServiceInterface providerDictionaryServiceInterface;
	@Autowired
	private  OperatorServerClassService provideServerClassService;

/*	@Autowired
	  public ProviderBusinessController(ProviderBusinessServiceIntegerface providerBusinessServiceIntegerface,
			AjaxJson ajaxJson) {
		super();
		this.providerBusinessServiceIntegerface = providerBusinessServiceIntegerface;
		this.ajaxJson = ajaxJson;
	}*/


/**
 * 
* @Title: save 
* @Description: 商户保存接口(这里用一句话描述这个方法的作用) 
* @param providerBusiness
* @param companyLogo
* @param companyLicenseReplica
* @param companyOtherReplica
* @param companyCorporationIDCardNoFront
* @param companyCorporationIDCardNoContrary
* @return    设定文件 
* @return AjaxJson    返回类型 
* @throws 
 */
	@ApiOperation(value="商户保存接口", notes="信息包括新增和修改")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public  synchronized AjaxJson save(@RequestBody ProviderBusiness providerBusiness) {
		AjaxJson ajaxJson=new AjaxJson();	
		if(providerBusiness!=null){
				String userid=providerBusiness.getPersonalUser().getId();
				ProviderBusiness business = providerBusinessServiceIntegerface.selectBusinessByUserid(userid);
				if(business!=null){
					PersonalUser personalUser=business.getPersonalUser();
					String isProvider=personalUser.getIsProvider();//服务商状态
					if(isProvider!=null){
						if(isProvider.equals("2")){
							return ajaxJson.setSuccess(true).setStatus(300).setData("已 服务商");
						}
					}
				}
			}
			List<OperatorServerClass> serverClass=provideServerClassService.selectByIdAndServerType(providerBusiness.getCommoditys(),1);
			if(serverClass.size()>0){
				providerBusiness.setIsRoomServer(1);
			}else{
				providerBusiness.setIsRoomServer(2);
			}
			providerBusiness.setCreateDate(new Date());
			ProviderBusiness   bus = providerBusinessServiceIntegerface.save(providerBusiness);
			if(null!=bus&&!bus.equals("")){
				ajaxJson.setSuccess(true).setStatus(200).setData(null);
			}else{
				ajaxJson.setSuccess(false).setStatus(250).setMsg("认证失败");
			}
			return ajaxJson;
	}
	
	@ApiOperation(value="商户信息", notes="详情")
    @GetMapping(value = "/sel")
	//@Transactional
    public  AjaxJson sel(String id ) {
		AjaxJson ajaxJson=new AjaxJson();
	 ProviderBusiness   bus = providerBusinessServiceIntegerface.selectpro(id);
	  ajaxJson.setSuccess(true).setStatus(200).setData(bus);
        return ajaxJson;

    }
	
	
	@ApiOperation(value="删除商户", notes="data返回0时可以删除 成功")
	@GetMapping(value="/del")
	@Transactional
    public  AjaxJson delebuspro(String id ) {
		AjaxJson ajaxJson=new AjaxJson();
		Integer   bus = providerBusinessServiceIntegerface.delectbus(id);
		if(bus==0){
	  ajaxJson.setSuccess(true).setStatus(200).setData(bus);
	  }else{
		  ajaxJson.setSuccess(false).setStatus(250).setMsg("商户下有服务不能删除");
	  }
        return ajaxJson;

    }
	 @ApiOperation(value="商户表分頁查", notes="分页显示角色数据")
	    @PostMapping(value = "/findPage")
	 //@Transactional
	public AjaxJson  getEntryByPageable(@RequestParam(value = "page", defaultValue = "0") Integer page,
            @RequestParam(value = "size", defaultValue = "2") Integer size,
            @RequestBody ProviderBusiness providerBusiness){
		 AjaxJson ajaxJson=new AjaxJson();
		 Specification<ProviderBusiness> spec = new Specification<ProviderBusiness>() {
			    public Predicate toPredicate(Root<ProviderBusiness> root,  
			            CriteriaQuery<?> query, CriteriaBuilder cb) {
			    	List<Predicate> lstPredicates = new ArrayList<Predicate>();
			    	if(providerBusiness.getBusinessName()!=null&&!providerBusiness.getBusinessName().equals("string")){
			        Predicate p1 = cb.like(root.get("businessName").as(String.class), "%"+providerBusiness.getBusinessName()+"%");
			        lstPredicates.add(p1);
			        }
			    	
			    	if(providerBusiness.getId()!=null&&!providerBusiness.getId().equals("string")){
			        Predicate p2 = cb.equal(root.get("id").as(String.class), providerBusiness.getId());
			        lstPredicates.add(p2);
			        }
			         
			        //把Predicate应用到CriteriaQuery中去,因为还可以给CriteriaQuery添加其他的功能，比如排序、分组啥的  
			    	Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
			    	
			        //添加排序的功能  
			      /*  query.orderBy(cb.desc(root.get("uuid").as(Integer.class)));*/  
			    	/*参数是数组*/
			          
			        return cb.and(lstPredicates.toArray(arrayPredicates));  
			    }  
			};
		  
		
	
		  Sort sort = new Sort(Sort.Direction.DESC, "id");
	        Pageable pageable = new PageRequest(page, size, sort);
	        Page<ProviderBusiness>  cd=providerBusinessRepository.findAll(spec, pageable);
	        
	        System.out.println();
	        return null;
	}
	
	 
	 @ApiOperation(value="商户上传图片返回地址信息", notes="商户上传logo返回地址信息")
	    @PostMapping(value = "/putImg")
	 @Transactional
	public  AjaxJson putImg(MultipartFile companyLogo,HttpServletResponse response) {
		 AjaxJson ajaxJson=new AjaxJson();
		 OSSUnitHelper ossunit=new OSSUnitHelper();
			OSSClient client=OSSUnitHelper.getOSSClient();
			String diskName = "datas/busimage/";
			
			String fileName = new Date().getTime() + (int) ((Math.random() * 9 + 1) * 100000)
					+ companyLogo.getOriginalFilename().substring(companyLogo.getOriginalFilename().indexOf("."));
	        String md5key = OSSUnitHelper.uploadObject2OSScopy(client, companyLogo, diskName,fileName);
	        String url=OSSUnitHelper.getUrl(client, diskName, fileName);
	        String urll=url.substring(4, url.length());
	        url="https"+urll;
	        System.out.println(url+"5");
	        if(url!=null&&!url.equals("")){
	        	ajaxJson.setSuccess(true).setStatus(200).setData(url);
	        	response.setContentType(url);
	        }
		 return ajaxJson;
		 
	 }
	 
	 
	 @ApiOperation(value="用户id查询商户信息", notes="用户id查询商户信息")
	 @RequestMapping(value = "/selectBusByUserid", method = RequestMethod.POST)
	 //@Transactional
	    public  AjaxJson selectBusByUserid(String userid ) {
		 AjaxJson ajaxJson=new AjaxJson();
		 ProviderBusiness   providerBusiness = providerBusinessServiceIntegerface.selectBusinessByUserid(userid);
		  if(null!=providerBusiness&&!providerBusiness.equals("")){
			  List<OperatorServerClass> serverClass=provideServerClassService.selectByIdAndServerLevel(providerBusiness.getCommoditys(),2);
			  providerBusiness.setPersonalUser(null);
			  providerBusiness.setProvideCommodity(null);
			  providerBusiness.setServerClasss(serverClass);
			  ajaxJson.setSuccess(true).setStatus(200).setData(providerBusiness);
		  }else{
			  ajaxJson.setSuccess(false).setStatus(250).setMsg("没有查询出信息");
		  }
	        return ajaxJson;

	    }
	 
	 
	 @ApiOperation(value="用户id查询商户信息", notes="用户id查询商户信息")
	 @RequestMapping(value = "/selectInitialData", method = RequestMethod.POST)
	 //@Transactional
	    public  AjaxJson selectInitialData() {
		 AjaxJson ajaxJson=new AjaxJson();
		 List<PerviderDictionary> pds=providerDictionaryServiceInterface.selectdicList("1");
		 
		 Integer serverLevel=1;
	    	List<OperatorServerClass> pss=provideServerClassService.getServerClassListForlevid(serverLevel);
	    	serverLevel=2;
	    	List<OperatorServerClass> pssTwo=provideServerClassService.getServerClassListForlevid(serverLevel);
	    	Map<String,Object> ss=new HashMap<>();
	    	ss.put("pss", pss);
	    	ss.put("pssTwo", pssTwo);
		 ss.put("pds", pds);
			
			  ajaxJson.setSuccess(true).setStatus(200).setData(ss);
		  
	        return ajaxJson;

	    }
	
	 @ApiOperation(value="修改商户经营范围", notes="通过商户id修改商户经营范围")
	 @RequestMapping(value = "/updateBusinessCommoditys", method = RequestMethod.POST)
	 public  AjaxJson updateBusinessCommoditys(@RequestBody ProviderBusinessServerRange providerBusiness)  {
		 AjaxJson ajaxJson=new AjaxJson();
		 try {
	 		providerBusinessServiceIntegerface.updateBusinessCommdoity(providerBusiness);
	 		ajaxJson.setSuccess(true).setStatus(200).setData("修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxJson.setSuccess(true).setStatus(250).setData("修改失败");
		}
	    return ajaxJson;
	 }
	 
	 @ApiOperation(value="根据商户ID查询商家管理中心首页的详情", notes="根据商户ID查询商家管理中心首页的详情")
	 @RequestMapping(value = "/selectBusinessById", method = RequestMethod.POST)
	 public  AjaxJson selectBusinessById(String businessId) {
		 AjaxJson ajaxJson=new AjaxJson();
		 try {
			Map<String, Object> reMap=providerBusinessServiceIntegerface.selectBusinessById(businessId);
			 ajaxJson.setSuccess(true).setStatus(200).setData(reMap);
		} catch (Exception e) {
			e.printStackTrace();
			ajaxJson.setSuccess(true).setStatus(200).setData("查询失败");
		}
		return ajaxJson;
		 
	 }
}
